import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import './index.scss'

class Dialog extends React.PureComponent {
  static propTypes = {
    title: PropTypes.oneOfType([PropTypes.element, PropTypes.string]).isRequired,
    description: PropTypes.oneOfType([PropTypes.element, PropTypes.string]).isRequired,
    buttons: PropTypes.arrayOf(
      PropTypes.shape({
        label: PropTypes.string,
        onClick: PropTypes.func,
        noDestroy: PropTypes.bool,
      }),
    ).isRequired,
    textAlign: PropTypes.string,
  }

  static defaultProps = {
    title: '标题',
    textAlign: 'left',
  }

  constructor(props) {
    super(props)
    this.state = { show: false }
    this.generatorBtns = this.generatorBtns.bind(this)
  }

  show() {
    this.setState({ show: true })
  }

  generatorBtns() {
    const { buttons } = this.props
    return buttons.length > 0 && buttons.map((button) => {
      const { label, onClick } = button
      return (
        <a
          href="javascript:void(0)"
          onClick={onClick}
          className="dialog-btn"
          key={label}
        >
          {label}
        </a>
      )
    })
  }

  render() {
    const { title, description, textAlign } = this.props
    const { show } = this.state
    const display = show ? 'block' : 'none'

    return (
      <div
        style={{ display }}
      >
        <div className="mask" />
        <div className="dialog">
          <div className="dialog-title">
            {title}
          </div>
          <div className="dialog-content" style={{ textAlign }}>
            {description}
          </div>
          <div className="dialog-btn-wrap">
            {this.generatorBtns()}
          </div>
        </div>
      </div>
    )
  }
}

Dialog.newInstance = function newDialogInstance(props) {
  const div = document.createElement('div')
  document.body.appendChild(div)

  const dialog = ReactDOM.render(<Dialog {...props} />, div)

  return {
    component: dialog,
    open() {
      dialog.show()
    },
    destroy() {
      ReactDOM.unmountComponentAtNode(div)
      document.body.removeChild(div)
    },
  }
}

export default Dialog
